import base64
from crypt import Random
from crypt import AES

def encrypt(key, plaintext):
    """
    AES加密算法实现
    :param key: 密钥
    :param plaintext: 明文
    :return: 密文
    """
    key = bytes.fromhex(key)
    plaintext = plaintext.encode('utf-8')
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    ciphertext = cipher.encrypt(plaintext)
    return base64.b64encode(iv + ciphertext).decode('utf-8')

def decrypt(key, ciphertext):
    """
    AES解密算法实现
    :param key: 密钥
    :param ciphertext: 密文
    :return: 明文
    """
    key = bytes.fromhex(key)
    ciphertext = base64.b64decode(ciphertext.encode('utf-8'))
    iv = ciphertext[:AES.block_size]
    cipher = AES.new(key, AES.MODE_CFB, iv)
    plaintext = cipher.decrypt(ciphertext[AES.block_size:]).decode('utf-8')
    return plaintext
